package ru.housewife.filters;

import ru.housewife.AppConstants;
import ru.housewife.form.UserForm;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * filter for synchronizing parallel requests from one user
 *
 * @author Alexander Troshanin
 */
public class SyncUserFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        UserForm user = (UserForm) ((HttpServletRequest) request).getSession().getAttribute(AppConstants.SESSION_USER);
        if (user != null) {
            if (!user.lock(10)) {
                // todo: redirect to somewhere
                // todo: test this!!!
                return;
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            if (user != null) {
                user.unlock();
            }
        }
    }

    @Override
    public void destroy() {
    }
}
